//
//  VoteHomepageController.m
//  meiyinxiang
//
//  Created by 媒印象 on 04/12/2017.
//  Copyright © 2017 hbjApple. All rights reserved.
//
#import "VoteHomepageController.h"
#import "ApplyActivityController.h"

#import "VoteHomepageCell.h"
#import "VoteHomepageSectionView.h"

#import <HexColor.h>
#import <MJRefresh.h>

#import "VoteListViewModel.h"

@interface VoteHomepageController ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_voteCollectionView;
    VoteListViewModel *_votelistViewModel;
    CGFloat VoteNavHeight;
}
@property (weak, nonatomic) IBOutlet UITextField *searchTextfild;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navBarHeightLayoutCons;

@end

@implementation VoteHomepageController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
  //  [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange) name:UITextFieldTextDidChangeNotification object:self.searchTextfild];
    VoteNavHeight = 135;
    if (IS_IPHONE_X) {
        self.navBarHeightLayoutCons.constant = 159;
        VoteNavHeight = 159;
    }
    AdjustsScrollViewInsetNever(self, _voteCollectionView);
    [self configCollectionView];
    [self addRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -PrivateMethod
- (void)textFieldChange{
    if (self.searchTextfild.text.length == 0) {
        [_votelistViewModel.searchResultViewModel removeAllObjects];
        [_voteCollectionView reloadData];
    }
}
- (void)loadData{
    if (_votelistViewModel == nil) {
        _votelistViewModel = [[VoteListViewModel alloc] init];
    }
    [_votelistViewModel loadDataWithIsPullUp:NO withResult:^(BOOL isSucess) {
        if (isSucess) {
            [_voteCollectionView reloadData];
            [_voteCollectionView.mj_header endRefreshing];
            [_voteCollectionView.mj_footer endRefreshing];
            
        }else{
            [_voteCollectionView.mj_header endRefreshing];
            [_voteCollectionView.mj_footer endRefreshingWithNoMoreData];
        }
       
    }];
}
- (void)loadMoreData{
    [_votelistViewModel loadDataWithIsPullUp:YES withResult:^(BOOL isSucess) {
        [_voteCollectionView reloadData];
        if (isSucess) {
            [_voteCollectionView.mj_footer endRefreshing];
        }else{
            [_voteCollectionView.mj_footer endRefreshingWithNoMoreData];
        }
       
    }];
}
- (void)addRefresh{

    WS(weakSelf);
    _voteCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [_voteCollectionView.mj_header beginRefreshing];
   _voteCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
       [weakSelf loadMoreData];
    }];
}
- (void)configCollectionView{
    if (_voteCollectionView == nil) {
        UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
        flowlayout.minimumLineSpacing = 8;
        flowlayout.minimumInteritemSpacing = 8;
        flowlayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
        CGFloat itemWidth = (ScreenWidth - 46)/2 ;
        CGFloat itemHeight = 221;
        flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowlayout.itemSize = CGSizeMake(itemWidth, itemHeight);
        //headerview
        flowlayout.headerReferenceSize=CGSizeMake(ScreenWidth, 55);
        _voteCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, VoteNavHeight, ScreenWidth, ScreenHeight - VoteNavHeight) collectionViewLayout:flowlayout];
        
    }
//    if (@available(iOS 11.0, *)) {
//        _voteCollectionView.backgroundColor = [UIColor colorNamed:@"EA4F48"];
//    } else {
        _voteCollectionView.backgroundColor = [UIColor colorWithHexString:@"EA4F48"];
        // Fallback on earlier versions
    //}
    _voteCollectionView.delegate = self;
    _voteCollectionView.dataSource = self;
    [_voteCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([VoteHomepageCell class]) bundle:nil] forCellWithReuseIdentifier:VoteHomepageCellReuseId];
    [_voteCollectionView registerNib:[UINib nibWithNibName:@"VoteHomepageSectionView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:VoteHompageSectionReusedId];
    [self.view addSubview:_voteCollectionView];
}
#pragma mark - LoadNib
+ (VoteHomepageController *)loadNibWithVoteVC{
    UINib *nib = [UINib nibWithNibName:@"VoteHomepageController" bundle:[NSBundle mainBundle]];
    return [[nib instantiateWithOwner:nil options:nil] lastObject];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _votelistViewModel.searchResultViewModel.count > 0 ? _votelistViewModel.searchResultViewModel.count : _votelistViewModel.viewModelArray.count;
}


- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    VoteHomepageCell *votecell = [collectionView dequeueReusableCellWithReuseIdentifier:VoteHomepageCellReuseId forIndexPath:indexPath];
    if (votecell == nil) {
        votecell = [VoteHomepageCell loadNibWithHomepageCell];
    }
    votecell.mSuperVC = self;
    VoteViewModel *viewModel = _votelistViewModel.searchResultViewModel.count > 0 ? _votelistViewModel.searchResultViewModel[indexPath.row] : _votelistViewModel.viewModelArray[indexPath.row];
    votecell.model = viewModel;
    return votecell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    VoteHomepageSectionView* reusableView;
    
    if (kind==UICollectionElementKindSectionHeader) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:VoteHompageSectionReusedId forIndexPath:indexPath];
        if (reusableView == nil) {
            reusableView = [VoteHomepageSectionView loadNibWithSectionView];
       }
    }
    [reusableView.applyActivityBtn addTarget:self action:@selector(applyAction) forControlEvents:UIControlEventTouchUpInside];

   // reusableView.backgroundColor=[UIColor orangeColor];
    
    return reusableView;
   
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.searchTextfild.isFirstResponder) {
        [self.searchTextfild resignFirstResponder];
    }
}
#pragma mark - Actions
//搜索按钮
- (IBAction)searchBtn:(id)sender {
    if (self.searchTextfild.isFirstResponder) {
        [self.searchTextfild resignFirstResponder];
    }
    [_votelistViewModel searchPersonWithKeyword:self.searchTextfild.text withResult:^(BOOL isSucess) {
        if (isSucess) {
            [_voteCollectionView reloadData];
        }
    }];
}
//返回按钮
- (IBAction)backBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
//点击报名按钮
- (void)applyAction{
    ApplyActivityController *appVC = [ApplyActivityController loadNibApplyVC];
    [self.navigationController pushViewController:appVC animated:YES];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:_searchTextfild];
}
@end
